const api = new (require('../../enhance/api').Api)()
const regeneratorRuntime = require('../../enhance/regenerator-runtime')

Page({

  data: {
    inputShowed: false,
    inputVal: '',
    goods_list: []
  },

  page_index: 1,

  async onLoad() {
    await this.search()
  },

  async search(e) {

    let search_key = this.data.inputVal
    if (e) this.page_index = 1

    try {
      let page = await api.search({ search_key, page_index: this.page_index })

      if (this.page_index == 1) {
        this.setData({ goods_list: page })
      }
      else {
        let { goods_list } = this.data
        goods_list.push(...page)
        this.setData({ goods_list })
      }
    }
    catch (error) {
      console.error(error)
    }
  },

  async onPullDownRefresh() {
    this.page_index = 1
    await this.search(null)
    wx.stopPullDownRefresh()
  },

  async onReachBottom() {
    this.page_index++
    await this.search(null)
  },

  showInput(e) {
    this.setData({ inputShowed: true })
  },

  hideInput(e) {
    this.setData({ inputVal: '', inputShowed: false })
  },

  async clearInput(e) {

    this.page_index = 1
    this.setData({ inputVal: '' })

    await this.search(e)
  },

  inputTyping(e) {
    this.setData({ inputVal: e.detail.value })
  }
})